import { defineStore } from 'pinia'
import type { StyleTemplate, ImageTask } from '../types'
import { getStyleTemplatesApi, getCategoriesApi } from '../api/style'
import { generateImageApi, getTaskStatusApi, getHistoryApi } from '../api/image'

export const useImageStore = defineStore('image', {
  state: () => ({
    styleTemplates: [] as StyleTemplate[],
    categories: [] as any[],
    currentTask: null as ImageTask | null,
    generationHistory: [] as ImageTask[],
    selectedStyle: null as StyleTemplate | null,
    uploadedImage: null as { url: string; filename: string } | null
  }),

  actions: {
    async loadStyleTemplates(category?: string) {
      try {
        const response = await getStyleTemplatesApi(category)
        this.styleTemplates = response.templates
        return { success: true }
      } catch (error: any) {
        return { success: false, error: error.message || '加载风格模板失败' }
      }
    },

    async loadCategories() {
      try {
        const response = await getCategoriesApi()
        this.categories = response.categories
        return { success: true }
      } catch (error: any) {
        return { success: false, error: error.message || '加载分类失败' }
      }
    },

    async generateImage(data: { 
      original_image_url: string
      style_template_id: number
      custom_prompt?: string 
    }) {
      try {
        const response = await generateImageApi(data)
        this.currentTask = response.task
        return { success: true, taskId: response.task_id }
      } catch (error: any) {
        return { success: false, error: error.message || '图片生成失败' }
      }
    },

    async getTaskStatus(taskId: string) {
      try {
        const response = await getTaskStatusApi(taskId)
        this.currentTask = response.task
        return { success: true, task: response.task }
      } catch (error: any) {
        return { success: false, error: error.message || '获取任务状态失败' }
      }
    },

    async loadHistory(page = 1, perPage = 10) {
      try {
        const response = await getHistoryApi(page, perPage)
        this.generationHistory = response.tasks
        return { success: true, data: response }
      } catch (error: any) {
        return { success: false, error: error.message || '加载历史记录失败' }
      }
    },

    setSelectedStyle(style: StyleTemplate) {
      this.selectedStyle = style
    },

    setUploadedImage(imageData: { url: string; filename: string }) {
      this.uploadedImage = imageData
    },

    clearCurrentTask() {
      this.currentTask = null
    }
  }
})